package org.meetunexpectedly.authority;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Description: 权限校验
 * 多个aop的情况下使用 @Order(1) 来指定顺序
 * @Author: pupil
 * @Date: 2024/09/03 下午 7:03
 */
@Aspect
@Component
public class AuthorityAop {

    @Autowired
    private HttpServletRequest request;

    /**
     * 校验AOP
     * @param proceedingJoinPoint
     * @param authority 校验注释
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authority)")
    public Object authority(ProceedingJoinPoint proceedingJoinPoint, Authority authority) throws Throwable {
        Boolean result;
        Method method;
        Object verifyObject;

        if (!AuthorityUtils.getPostAuthority()) {
            if (AuthorityUtils.getGlobalVerifyState()) {
                // 全局校验c类
                Class globalVerify = AuthorityUtils.getGlobalVerify();
                verifyObject = globalVerify.newInstance();
                method = globalVerify.getMethod("authorityVerify", HttpServletRequest.class, String[].class);
                result = (Boolean) method.invoke(verifyObject, request, authority.value());
                if (!result) throw new AuthenticationException("权限不足");
            }
        }

        return proceedingJoinPoint.proceed();
    }
}
